package com.bz.xtcx.manager.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

//@Component
public class KeyValueTransUtil {
    /** 日志. */
    private final Logger logger = LoggerFactory.getLogger(KeyValueTransUtil.class);

    private static KeyValueTransUtil kvtUtil = new KeyValueTransUtil();

//    @Autowired
//    private BusUserFormMapper busUserFormMapper;

    /** 省市区 */
    private Map<String, String> pcaaKeyValMap = new HashMap<String, String>();
    private Map<String, List<String>> pcaaValKeyMap = new HashMap<String, List<String>>();

    /** 专家 */
    private Map<String, Map<String, String>> zjKeyValMap = new HashMap<String, Map<String, String>>();
    private Map<String, Map<String, String>> zjValKeyMap = new HashMap<String, Map<String, String>>();

    /** 企业 */
    private Map<String, Map<String, String>> qyKeyValMap = new HashMap<String, Map<String, String>>();
    private Map<String, Map<String, String>> qyValKeyMap = new HashMap<String, Map<String, String>>();

    /** 服务机构 */
    private Map<String, Map<String, String>> fwjgKeyValMap = new HashMap<String, Map<String, String>>();
    private Map<String, Map<String, String>> fwjgValKeyMap = new HashMap<String, Map<String, String>>();

    /** 需求 */
    private Map<String, Map<String, String>> xqKeyValMap = new HashMap<String, Map<String, String>>();
    private Map<String, Map<String, String>> xqValKeyMap = new HashMap<String, Map<String, String>>();

    /** 成果 */
    private Map<String, Map<String, String>> cgKeyValMap = new HashMap<String, Map<String, String>>();
    private Map<String, Map<String, String>> cgValKeyMap = new HashMap<String, Map<String, String>>();

    private boolean isInit = false;

    private KeyValueTransUtil() {
//        init();
    }

    private synchronized void init() {
        if (!isInit) {
            if (loadPcaa() && loadZJ() && loadQY() && loadFWJG() && loadXQ() && loadCG()) {
                isInit = true;
            }
        }
    }

    private synchronized boolean loadPcaa() {
//        logger.info("导入省市区数据开始");
        if (0 == pcaaKeyValMap.size() || 0 == pcaaValKeyMap.size()) {
            pcaaKeyValMap.clear();
            pcaaValKeyMap.clear();
        } else {
            return true;
        }
        try {
            InputStream stream = getClass().getClassLoader().getResourceAsStream("pcaa.json");
            File targetFile = new File("conf/pcaa.json");
            FileUtils.copyInputStreamToFile(stream, targetFile);
            String jsonStr = FileUtils.readFileToString(targetFile, "UTF-8");
//            String fPath = getClass().getClassLoader().getResource("pcaa.json").toString();
//            if (fPath.contains(":")) {
//                fPath = fPath.replace("file:/","");
//            }
//            logger.info("省市区文件路径：" + fPath);
//            String jsonStr = FileUtils.readFileToString(new File(fPath), "UTF-8");
            JSONObject pcaaJson = JSON.parseObject(jsonStr);
            Set<String> keys = pcaaJson.keySet();
            Set<String> subKeys = null;
            JSONObject subPcaaJson = null;
            for (String mKey : keys) {
                subPcaaJson = pcaaJson.getJSONObject(mKey);
                subKeys = subPcaaJson.keySet();
                for (String sKey : subKeys) {
                    pcaaKeyValMap.put(sKey, subPcaaJson.getString(sKey));
                    if (null == pcaaValKeyMap.get(subPcaaJson.getString(sKey))) {
                        pcaaValKeyMap.put(subPcaaJson.getString(sKey), new ArrayList<String>());
                    }
                    pcaaValKeyMap.get(subPcaaJson.getString(sKey)).add(sKey);
                }
            }
        } catch (IOException e) {
            logger.error("读取省市区文件是异常", e);
            return false;
        } catch (Exception e) {
            logger.error("解析省市区文件是异常", e);
            return false;
        }
        return true;
    }

    private synchronized boolean loadZJ() {
//        logger.info("导入专家数据开始");
        if (0 == zjKeyValMap.size() || 0 == zjValKeyMap.size()) {
            zjKeyValMap.clear();
            zjValKeyMap.clear();
        } else {
            return true;
        }

        try {
            InputStream stream = getClass().getClassLoader().getResourceAsStream("zj.json");
            File targetFile = new File("conf/zj.json");
            FileUtils.copyInputStreamToFile(stream, targetFile);
            String jsonStr = FileUtils.readFileToString(targetFile, "UTF-8");
//            BusUserForm buf = busUserFormMapper.findByType(1);
//            String jsonStr = buf.getDetail();
            JSONObject mainJson = JSON.parseObject(jsonStr);
            Set<String> mainkeys = mainJson.keySet();
            Set<String> subKeys = null;
            JSONArray subKVArr = null;
            JSONObject subJson = null;
            Map<String, String> subKvMap = null;
            Map<String, String> subVkMap = null;
            for (String mKey : mainkeys) {
                subKvMap = new HashMap<String, String>();
                subVkMap = new HashMap<String, String>();
                subKVArr = mainJson.getJSONArray(mKey);
                for (int i = 0; i < subKVArr.size(); i++) {
                    subJson = subKVArr.getJSONObject(i);
                    subKeys = subJson.keySet();
                    for (String sKey : subKeys) {
                        subKvMap.put(sKey, subJson.getString(sKey));
                        subVkMap.put(subJson.getString(sKey), sKey);
                    }
                }
                zjKeyValMap.put(mKey, subKvMap);
                zjValKeyMap.put(mKey, subVkMap);
            }
//        } catch (IOException e) {
//            logger.error("读取专家文件是异常", e);
        } catch (Exception e) {
            logger.error("解析专家配置数据时异常", e);
            return false;
        }
        return true;
    }

    private synchronized boolean loadQY() {
//        logger.info("导入企业数据开始");
        if (0 == qyKeyValMap.size() || 0 == qyValKeyMap.size()) {
            qyKeyValMap.clear();
            qyValKeyMap.clear();
        } else {
            return true;
        }
        try {
            InputStream stream = getClass().getClassLoader().getResourceAsStream("qy.json");
            File targetFile = new File("conf/qy.json");
            FileUtils.copyInputStreamToFile(stream, targetFile);
            String jsonStr = FileUtils.readFileToString(targetFile, "UTF-8");
//            BusUserForm buf = busUserFormMapper.findByType(2);
//            String jsonStr = buf.getDetail();
            JSONObject mainJson = JSON.parseObject(jsonStr);
            Set<String> mainkeys = mainJson.keySet();
            Set<String> subKeys = null;
            JSONArray subKVArr = null;
            JSONObject subJson = null;
            Map<String, String> subKvMap = null;
            Map<String, String> subVkMap = null;
            for (String mKey : mainkeys) {
                subKvMap = new HashMap<String, String>();
                subVkMap = new HashMap<String, String>();
                subKVArr = mainJson.getJSONArray(mKey);
                for (int i = 0; i < subKVArr.size(); i++) {
                    subJson = subKVArr.getJSONObject(i);
                    subKeys = subJson.keySet();
                    for (String sKey : subKeys) {
                        subKvMap.put(sKey, subJson.getString(sKey));
                        subVkMap.put(subJson.getString(sKey), sKey);
                    }
                }
                qyKeyValMap.put(mKey, subKvMap);
                qyValKeyMap.put(mKey, subVkMap);
            }
//        } catch (IOException e) {
//            logger.error("读取企业文件是异常", e);
        } catch (Exception e) {
            logger.error("解析企业配置数据时异常", e);
            return false;
        }
        return true;
    }

    private synchronized boolean loadFWJG() {
//        logger.info("导入服务机构数据开始");
        if (0 == fwjgKeyValMap.size() || 0 == fwjgValKeyMap.size()) {
            fwjgKeyValMap.clear();
            fwjgValKeyMap.clear();
        } else {
            return true;
        }
        try {
            InputStream stream = getClass().getClassLoader().getResourceAsStream("fwjg.json");
            File targetFile = new File("conf/fwjg.json");
            FileUtils.copyInputStreamToFile(stream, targetFile);
            String jsonStr = FileUtils.readFileToString(targetFile, "UTF-8");
//            BusUserForm buf = busUserFormMapper.findByType(3);
//            String jsonStr = buf.getDetail();
            JSONObject mainJson = JSON.parseObject(jsonStr);
            Set<String> mainkeys = mainJson.keySet();
            Set<String> subKeys = null;
            JSONArray subKVArr = null;
            JSONObject subJson = null;
            Map<String, String> subKvMap = null;
            Map<String, String> subVkMap = null;
            for (String mKey : mainkeys) {
                subKvMap = new HashMap<String, String>();
                subVkMap = new HashMap<String, String>();
                subKVArr = mainJson.getJSONArray(mKey);
                for (int i = 0; i < subKVArr.size(); i++) {
                    subJson = subKVArr.getJSONObject(i);
                    subKeys = subJson.keySet();
                    for (String sKey : subKeys) {
                        subKvMap.put(sKey, subJson.getString(sKey));
                        subVkMap.put(subJson.getString(sKey), sKey);
                    }
                }
                fwjgKeyValMap.put(mKey, subKvMap);
                fwjgValKeyMap.put(mKey, subVkMap);
            }
//        } catch (IOException e) {
//            logger.error("读取服务机构文件是异常", e);
        } catch (Exception e) {
            logger.error("解析服务机构配置数据时异常", e);
            return false;
        }
        return true;
    }

    private synchronized boolean loadXQ() {
//        logger.info("导入需求数据开始");
        if (0 == xqKeyValMap.size() || 0 == xqValKeyMap.size()) {
            xqKeyValMap.clear();
            xqValKeyMap.clear();
        } else {
            return true;
        }
        try {
            InputStream stream = getClass().getClassLoader().getResourceAsStream("xq.json");
            File targetFile = new File("conf/xq.json");
            FileUtils.copyInputStreamToFile(stream, targetFile);
            String jsonStr = FileUtils.readFileToString(targetFile, "UTF-8");
//            BusUserForm buf = busUserFormMapper.findByType(7);
//            String jsonStr = buf.getDetail();
            JSONObject mainJson = JSON.parseObject(jsonStr);
            Set<String> mainkeys = mainJson.keySet();
            Set<String> subKeys = null;
            JSONArray subKVArr = null;
            JSONObject subJson = null;
            Map<String, String> subKvMap = null;
            Map<String, String> subVkMap = null;
            for (String mKey : mainkeys) {
                subKvMap = new HashMap<String, String>();
                subVkMap = new HashMap<String, String>();
                subKVArr = mainJson.getJSONArray(mKey);
                for (int i = 0; i < subKVArr.size(); i++) {
                    subJson = subKVArr.getJSONObject(i);
                    subKeys = subJson.keySet();
                    for (String sKey : subKeys) {
                        subKvMap.put(sKey, subJson.getString(sKey));
                        subVkMap.put(subJson.getString(sKey), sKey);
                    }
                }
                xqKeyValMap.put(mKey, subKvMap);
                xqValKeyMap.put(mKey, subVkMap);
            }
//        } catch (IOException e) {
//            logger.error("读取需求文件是异常", e);
        } catch (Exception e) {
            logger.error("解析需求配置数据时异常", e);
            return false;
        }
        return true;
    }

    private synchronized boolean loadCG() {
//        logger.info("导入成果数据开始");
        if (0 == cgKeyValMap.size() || 0 == cgValKeyMap.size()) {
            cgKeyValMap.clear();
            cgValKeyMap.clear();
        } else {
            return true;
        }
        try {
            InputStream stream = getClass().getClassLoader().getResourceAsStream("cg.json");
            File targetFile = new File("conf/cg.json");
            FileUtils.copyInputStreamToFile(stream, targetFile);
            String jsonStr = FileUtils.readFileToString(targetFile, "UTF-8");
//            BusUserForm buf = busUserFormMapper.findByType(6);
//            String jsonStr = buf.getDetail();
            JSONObject mainJson = JSON.parseObject(jsonStr);
            Set<String> mainkeys = mainJson.keySet();
            Set<String> subKeys = null;
            JSONArray subKVArr = null;
            JSONObject subJson = null;
            Map<String, String> subKvMap = null;
            Map<String, String> subVkMap = null;
            for (String mKey : mainkeys) {
                subKvMap = new HashMap<String, String>();
                subVkMap = new HashMap<String, String>();
                subKVArr = mainJson.getJSONArray(mKey);
                for (int i = 0; i < subKVArr.size(); i++) {
                    subJson = subKVArr.getJSONObject(i);
                    subKeys = subJson.keySet();
                    for (String sKey : subKeys) {
                        subKvMap.put(sKey, subJson.getString(sKey));
                        subVkMap.put(subJson.getString(sKey), sKey);
                    }
                }
                cgKeyValMap.put(mKey, subKvMap);
                cgValKeyMap.put(mKey, subVkMap);
            }
//        } catch (IOException e) {
//            logger.error("读取成果文件是异常", e);
        } catch (Exception e) {
            logger.error("解析成果配置数据时异常", e);
            return false;
        }
        return true;
    }

    public synchronized static KeyValueTransUtil getInstance() {
        return kvtUtil;
    }

    public synchronized static String getPcaaValByKey(String key) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key)) {
//            throw new XtcxException("省市区转换Key为空");
            return "";
        }
        return kvtUtil.pcaaKeyValMap.get(key);
    }

//    public synchronized static String getPcaaKeyByVal(String val) {
//        kvtUtil.init();
//        if (WzStrUtil.isBlank(val)) {
////            throw new XtcxException("省市区转换Value为空");
//            return "";
//        }
//        return kvtUtil.pcaaValKeyMap.get(val);
//    }

    public synchronized static String getPcaaKeyByVal(String pType, String pKey, String val) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(val)) {
//            throw new XtcxException("省市区转换Value为空");
            return "";
        }
        List<String> kLs = kvtUtil.pcaaValKeyMap.get(val);
        if (null == kLs || 0 == kLs.size()) {
            return "";
        }
        if (WzStrUtil.isNotBlank(pKey)) {
            if ("p".equals(pType)) {
                for (String ss : kLs) {
                    if (ss.substring(0, 2).equals(pKey.substring(0, 2))) {
                        return ss;
                    }
                }
            } else if ("c".equals(pType)) {
                for (String ss : kLs) {
                    if (ss.substring(0, 4).equals(pKey.substring(0, 4))) {
                        return ss;
                    }
                }
            } else {
                return kLs.get(0);
            }
        } else {
            return kLs.get(0);
        }
        return "";
    }

    public synchronized static String getZJValByKey(String key, String skey) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(skey)) {
//            throw new XtcxException("专家转换Key为空");
            return "";
        }
        return kvtUtil.zjKeyValMap.get(key).get(skey);
    }

    public synchronized static String getZJKeyByVal(String key, String val) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(val)) {
//            throw new XtcxException("专家转换Value为空");
            return "";
        }
        return kvtUtil.zjValKeyMap.get(key).get(val);
    }

    public synchronized static String getQYValByKey(String key, String skey) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(skey)) {
//            throw new XtcxException("企业转换Key为空");
            return "";
        }
        return kvtUtil.qyKeyValMap.get(key).get(skey);
    }

    public synchronized static String getQYKeyByVal(String key, String val) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(val)) {
//            throw new XtcxException("企业转换Value为空");
            return "";
        }
        return kvtUtil.qyValKeyMap.get(key).get(val);
    }

    public synchronized static String getFWJGValByKey(String key, String skey) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(skey)) {
//            throw new XtcxException("服务机构转换Key为空");
            return "";
        }
        return kvtUtil.fwjgKeyValMap.get(key).get(skey);
    }

    public synchronized static String getFWJGKeyByVal(String key, String val) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(val)) {
//            throw new XtcxException("服务机构转换Value为空");
            return "";
        }
        return kvtUtil.fwjgValKeyMap.get(key).get(val);
    }

    public synchronized static String getXQValByKey(String key, String skey) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(skey)) {
//            throw new XtcxException("需求转换Key为空");
            return "";
        }
        return kvtUtil.xqKeyValMap.get(key).get(skey);
    }

    public synchronized static String getXQKeyByVal(String key, String val) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(val)) {
//            throw new XtcxException("需求转换Value为空");
            return "";
        }
        return kvtUtil.xqValKeyMap.get(key).get(val);
    }

    public synchronized static String getCGValByKey(String key, String skey) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(skey)) {
//            throw new XtcxException("成果转换Key为空");
            return "";
        }
        return kvtUtil.cgKeyValMap.get(key).get(skey);
    }

    public synchronized static String getCGKeyByVal(String key, String val) {
        kvtUtil.init();
        if (WzStrUtil.isBlank(key) || WzStrUtil.isBlank(val)) {
//            throw new XtcxException("成果转换Value为空");
            return "";
        }
        return kvtUtil.cgValKeyMap.get(key).get(val);
    }

    /**
     * key数组转换成显示值数组.
     * @param confJson 配置Json
     * @param key 主关键字
     * @param values key数组字符串
     * @return 值字符串
     */
    public String transKey2Ch(JSONObject confJson, String key, String values) {
        if (null == confJson || WzStrUtil.isBlank(key) || WzStrUtil.isBlank(values)) {
            return "";
        }
        StringBuilder chStr = new StringBuilder("");
        try {
            JSONArray valArr = JSONArray.parseArray(values);
            JSONArray confArr = confJson.getJSONArray(key);
            String vvo = null;
            for (int i = 0; i < valArr.size(); i++) {
                vvo = valArr.getString(i);
                for (int j = 0; j < confArr.size(); j++) {
                    if (confArr.getJSONObject(j).get(vvo) != null) {
                        if (i == 0) {
                            chStr.append(confArr.getJSONObject(j).get(vvo));
                        } else {
                            chStr.append(",").append(confArr.getJSONObject(j).get(vvo));
                        }
                        break;
                    }
                }
            }
        }catch (Exception ex) {
            logger.error("KV数组转换时异常", ex);
            return "--";
        }
        return WzStrUtil.defaultIfBlank(chStr.toString(), "--");
    }

    public static String transCh(JSONObject confJson, String key, String values) {
        return kvtUtil.transKey2Ch(confJson, key, values);
    }

    /**
     * key数组转换成单一显示值.
     * @param confJson 配置Json
     * @param key 主关键字
     * @param value key数组字符串
     * @return 值字符串
     */
    public String transKey2OneCh(JSONObject confJson, String key, String value) {
        if (null == confJson || WzStrUtil.isBlank(key) || WzStrUtil.isBlank(value)) {
            return "";
        }
        StringBuilder chStr = new StringBuilder("");
        try {
            JSONArray confArr = confJson.getJSONArray(key);
            for (int i = 0; i < confArr.size(); i++) {
                if (confArr.getJSONObject(i).get(value) != null) {
                    chStr.append(confArr.getJSONObject(i).get(value));
                    break;
                }
            }
        } catch (Exception ex) {
            logger.error("KV转换时异常", ex);
            return "--";
        }
        return WzStrUtil.defaultIfBlank(chStr.toString(), "-");
    }

    public static String transChOnly(JSONObject confJson, String key, String value) {
        return kvtUtil.transKey2OneCh(confJson, key, value);
    }

    public String getPcaaCh(String key) {
        if (WzStrUtil.isBlank(key)) {
            return "";
        }
        StringBuilder pcaaStr = new StringBuilder("");
        try {
            JSONArray keyArr = JSONArray.parseArray(key);
            if (0 < keyArr.size()) {
                pcaaStr.append(getPcaaValByKey(keyArr.getString(0)));
            }
            if (1 < keyArr.size()) {
                pcaaStr.append(",").append(getPcaaValByKey(keyArr.getString(1)));
            }
            if (2 < keyArr.size()) {
                pcaaStr.append(",").append(getPcaaValByKey(keyArr.getString(2)));
            }
        } catch (Exception ex) {
            logger.error("地域KV转换时异常", ex);
            return "--";
        }
        String result = pcaaStr.toString();
        if(!StringUtils.isEmpty(result)){
            if (result.endsWith(",")) {
                result = result.substring(0,result.length()-1);
            }
        }
        return WzStrUtil.defaultIfBlank(result, "-");
    }

    public static String getPcaa(String keys) {
        return kvtUtil.getPcaaCh(keys);
    }

    public static Map<String, String> getPcaaKVMap() {
        kvtUtil.init();
        return kvtUtil.pcaaKeyValMap;
    }

    public static Map<String, List<String>> getPcaaVKMap() {
        kvtUtil.init();
        return kvtUtil.pcaaValKeyMap;
    }
}
